local type,tostring,select,pairs,ipairs,assert=type,tostring,select,pairs,ipairs,assert
local string_len,string_rep,string_match,string_format,string_find,string_byte=
	  string.len,string.rep,string.match,string.format,string.find,string.byte
local table_insert,table_remove=
	  table.insert,table.remove
module(..., package.seeall)

require'zdc.logger'
require'zdc.fieldutil'


local dfskey=zdc.fieldutil.dfskey

DplSvc = {}
local DplSvc_mt = {__metatable={}, __index=DplSvc}


function new(dal,con_module, con_params, secugroups,auth,logger)
	local repo = setmetatable({_is_svc=true}, DplSvc_mt)
	repo.dal=dal
	assert(con_module,'bad con_module: '..tostring(con_module))
	if type(con_module)=='table' then
		repo._svc = con_module
	else
		local dbm = require(con_module)
		repo._svc = dbm.new(con_params)
	end
	repo._secugroups = secugroups or {}
	repo._auth=auth
	repo._log = logger
	repo:_reset_cache()
	return repo
end

function BuildDpl(dal,config)
	local config = config or {}
	local dpl = new(dal,config.CLI.MODULE,config.CLI.PARAMS,config.secugroups,config.auth,config.log or zdc.logger.defaultlog)
	dpl._no_reset_cache=config.NO_RESET_CACHE
	return dpl
end

function DplSvc:_reset_cache(force)
	if force or not self._no_reset_cache then
		self._cache = {}
	end
	if force then
		if self._svc.reset_cache then
			self._svc:reset_cache()
		end
	end
end

function DplSvc:_get_con(id)
	return self._svc:get_connect(id)
end

function DplSvc:_call_node(user,id,act,...)
	local con=self:_get_con(id)
	if not con then return false,'no connect for:'..tostring(id) end
	return con:_call_msg(user,self.dal,id,act,...)
end

function DplSvc:_acall_node(user,id,cb,act,...)
	local con=self:_get_con(id)
	if not con then return false,'no connect for:'..tostring(id) end
	return con:_acall_msg(user,self.dal,cb,id,act,...)
end
